import json
import os
from datetime import datetime, timedelta
from .dingding import send_dingtalk_markdown
from .utils import get_project_root

class PushService:
    def __init__(self, title, record_file="sent_signals.json"):
        project_root = get_project_root()
        record_file = f"{project_root}/{record_file}"
        self.title = title
        self.taskList = []
        self.record_file = record_file
        self.sent_signals = self._load_records()  # 初始化时加载历史记录

    def _load_records(self):
        """从文件加载已推送记录"""
        if os.path.exists(self.record_file):
            with open(self.record_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
                # 将字符串时间转换为datetime对象
                return {k: datetime.fromisoformat(v) for k, v in data.items()}
        return {}

    def _save_records(self):
        """保存记录到文件"""
        # 先清理过期记录（保留24小时内的）
        self._clean_old_records(hours=24)
        
        # 转换datetime为可序列化的字符串
        data = {k: v.isoformat() for k, v in self.sent_signals.items()}
        with open(self.record_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def _clean_old_records(self, hours=24):
        """清理超过指定小时的旧记录"""
        cutoff = datetime.now() - timedelta(hours=hours)
        self.sent_signals = {
            k: v for k, v in self.sent_signals.items()
            if v > cutoff
        }

    def add_push_item(self, after_signal, instId, extent=[]):
        signal_key = f"{instId}_{after_signal.name}"
        
        if self._is_signal_sent(signal_key):
            return False

        direction = '做多' if after_signal['signal'] > 0 else '做空'

        extentText = ''
        for text in extent:
            extentText += f"{text}"
        self.taskList.extend([
            f'{instId} {direction}',
            f'{extentText}',
            f'K线时间：{after_signal.name}',
            '========================='
        ])
        
        self._mark_signal_sent(signal_key)
        return True

    def _is_signal_sent(self, signal_key):
        return signal_key in self.sent_signals

    def _mark_signal_sent(self, signal_key):
        self.sent_signals[signal_key] = datetime.now()
        self._save_records()  # 每次更新后立即保存

    def push_message(self):
        if not self.taskList:
            return

        text = f"### {self.title}\n\n" + "\n\n".join(self.taskList)
        print(text)
        send_dingtalk_markdown(self.title, text)
        self.taskList = []